package sv_cmd

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"venus/core"
	"venus/util/zlog"
)

type SvCmd struct {
	BindMap map[string]func([]string) //处理列表
}

var _Sv *SvCmd

func NewSv(fnRegisters ...func()) *SvCmd {
	_Sv = new(SvCmd)
	_Sv.BindMap = make(map[string]func([]string))
	for _, fn := range fnRegisters {
		fn()
	}
	return _Sv
}

func (sv *SvCmd) Init() {
	zlog.Info(sv.Name() + " Init")

	core.BindMsgExec(core.MsgTypeCmd, sv.Exec)
}

func (sv *SvCmd) Run() {
	zlog.Info(sv.Name() + " Run")

	for {
		f := bufio.NewReader(os.Stdin) //读取输入的内容
		var msg string
		msg, _ = f.ReadString('\n') //定义一行输入的内容分隔符。
		msg = strings.ReplaceAll(msg, "\r\n", "")
		if len(msg) > 0 && len(msg) < 100 {
			addMsg(msg)
		}
	}
}

func (sv *SvCmd) Destroy() {
	zlog.Info(sv.Name() + " Destroy")
}

func (sv *SvCmd) Name() string {
	return "SvCmd"
}

func (sv *SvCmd) Bind(cmd string, fn func([]string)) {
	sv.BindMap[cmd] = fn
}

func (sv *SvCmd) Binds(cs []string, fn func([]string)) {
	for _, v := range cs {
		sv.Bind(v, fn)
	}
}

func (sv *SvCmd) Exec(e *core.Msg) {
	cmd := e.Data.(*CmdInfo)
	fn, ok := sv.BindMap[cmd.Cmd]
	if ok {
		fn(cmd.Args)
	} else {
		fmt.Println("无效指令：", cmd)
	}
}

func addMsg(text string) {
	msg := &core.Msg{
		Type: core.MsgTypeCmd,
		Data: NewCmdInfo(text),
	}
	core.AddMsg(msg)
}
